import {ref, reactive} from 'vue'
import {ElMessage} from 'element-plus'
import {statisticsOrder, getCourseStatistics, getChapterStatistics} from '../../../../../api/statices'

export function useTable() {
  // 表格数据
  const tableData = ref([])
  const loading = ref(false)
  const total = ref(0)

  // 查询参数
  const queryParams = reactive({
    goodsId: null, // 课程名称
    buyerMobile: null, // 手机号
    buyerName: null, // 学员姓名
    createStartDate: null, // 创建时间开始范围
    createEndDate: null, // 创建时间结束范围
    pageDomain: {
      pageNum: 1,
      pageSize: 20,
      orderByColumn: null,
      isAsc: null,
      reasonable: false
    }
  })

  // 添加排序参数
  const sortParams = reactive({
    orderBy: '',
    isAsc: true
  })

  // 记录已加载的数据

  // 处理排序变化
  const handleSortChange = ({prop, order}) => {
    queryParams.pageDomain.orderByColumn = prop
    queryParams.pageDomain.isAsc = order === 'ascending' ? 'asc' : 'desc'
    initPage()
  }

  // 初始化页面数据
  const initPage = () => {
    tableData.value = []
    loading.value = true
    const params = {
      goodsId: queryParams.goodsId,
      buyerMobile: queryParams.buyerMobile,
      buyerName: queryParams.buyerName,
      createStartDate: queryParams.createStartDate,
      createEndDate: queryParams.createEndDate,
      pageDomain: {
        pageNum: queryParams.pageDomain.pageNum,
        pageSize: queryParams.pageDomain.pageSize,
        orderByColumn: queryParams.pageDomain.orderByColumn,
        isAsc: queryParams.pageDomain.isAsc,
        reasonable: false
      } 
    }
    // 获取订单数据
    statisticsOrder(params).then(res => {
      tableData.value = res.rows || []
      total.value = res.total || 0
      loading.value = false
    }).catch(() => {
      loading.value = false
    })
  }

  // 查询按钮操作
  const handleQuery = (e) => {
    queryParams.goodsId = e.goodsId
    queryParams.buyerMobile = e.buyerMobile
    queryParams.buyerName = e.buyerName
    queryParams.createStartDate = e.createStartDate
    queryParams.createEndDate = e.createEndDate
    queryParams.pageDomain.pageNum = 1
    initPage()
  }

  // 重置按钮操作
  const resetQuery = () => {
    // 重置查询参数
    queryParams.goodsId = ''
    queryParams.buyerMobile = ''
    queryParams.buyerName = ''
    queryParams.createStartDate = ''
    queryParams.createEndDate = ''

    // 重置分页参数
    queryParams.pageDomain.pageNum = 1
    queryParams.pageDomain.pageSize = 20
    queryParams.pageDomain.orderByColumn = ''
    queryParams.pageDomain.isAsc = ''
    tableData.value = []
    // 重新查询
    initPage()
  }

  // 处理课程展开 - 加载章节数据
  const handleCourseExpand = async ({expandedRow, expanded, parentRow}) => {
    if (expanded) {
      loading.value = true
      try {
        getCourseStatistics({
          orderItemId: parentRow.id, // 子订单id
          userId: parentRow.buyerId, // 用户id
          courseId: expandedRow.id // 课程id
        }).then(res => {
          if (!expandedRow.children) {
            expandedRow.children = []
          }
          expandedRow.children = res.rows
        })
      } catch (error) {
        console.error('获取课程数据失败：', error)
        ElMessage.error('获取课程数据失败')
      } finally {
        loading.value = false
      }
    }
  }

  // 处理展开行 - 加载课程数据
  const handleExpand = async (row, expanded) => {
    if (expanded) {
      loading.value = true
      try {
        getChapterStatistics({
          orderItemId: row.id,
          userId: row.buyerId
        }).then(res => {
          if (!row.children) {
            row.children = []
          }
          row.children = res.rows
        })
      } catch (error) {
        console.error('获取章节数据失败：', error)
        ElMessage.error('获取章节数据失败')
      } finally {
        loading.value = false
      }
    }
  }

  // 处理每页显示数量变化
  const handleSizeChange = (val) => {
    queryParams.pageDomain.pageSize = val
    queryParams.pageDomain.pageNum = 1
    initPage()
  }

  // 处理页码变化
  const handleCurrentChange = (val) => {
    queryParams.pageDomain.pageNum = val
    initPage()
  }

  return {
    tableData,
    loading,
    total,
    queryParams,
    initPage,
    handleQuery,
    resetQuery,
    handleSortChange,
    handleExpand,
    handleCourseExpand,
    handleSizeChange,
    handleCurrentChange
  }
}
